# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=libatomic_ops
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=7.8.0
pkgrel=1
pkgdesc="Provides semi-portable access to hardware provided atomic memory operations (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://www.hboehm.info/gc"
license=('spdx:GPL-2.0' 'spdx:MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/ivmai/${_realname}/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        001-fix-pkgconfig.patch)
sha256sums=('15676e7674e11bda5a7e50a73f4d9e7d60452271b8acf6fd39a71fefdf89fa31'
            '4d8a9037a3f6cd831f1cfe9dcb9f51c993b767f0115018306ca547acbdd5b4e8')

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-pkgconfig.patch
}

build() {
  mkdir -p ${srcdir}/build-${MSYSTEM} && cd ${srcdir}/build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${MSYSTEM} == MINGW64 || ${MSYSTEM} == UCRT64 ]]; then
    _extra_config+=("-Denable_atomic_intrinsics=OFF")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  "${MINGW_PREFIX}"/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
    -DBUILD_SHARED_LIBS=ON \
    -DCMAKE_SHARED_LIBRARY_NAME_WITH_VERSION=ON \
    "${_extra_config[@]}" \
    ../${_realname}-${pkgver}

  "${MINGW_PREFIX}"/bin/cmake.exe --build .
}

check() {
  cd ${srcdir}/build-${MSYSTEM}
  "${MINGW_PREFIX}"/bin/cmake.exe -Dbuild_tests=ON ../${_realname}-${pkgver}
  "${MINGW_PREFIX}"/bin/cmake.exe --build .
  "${MINGW_PREFIX}"/bin/ctest || echo "Tests failed"
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .

  install -D -m644 ${srcdir}/${_realname}-${pkgver}/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
